﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Torimi.Wiki.Interfaces;
using Torimi.Wiki.DataObjects;
using System.Xml;
using System.Globalization;

namespace Torimi.Wiki.Services
{
	/// <summary>
	/// XmlBackupService class.
	/// </summary>
	public class XmlBackupService : IBackupService
	{
		/// <summary>
		/// Performs a complete wiki backup.
		/// </summary>
		/// <param name="settings">The settings.</param>
		/// <param name="wikiInstance">The wiki instance.</param>
		public void PerformCompleteWikiBackup(Dictionary<string, string> settings, IWiki wikiInstance)
		{
			var exporterSettings = new XmlBackupServiceSettings(settings);
			var fileAndPath = System.IO.Path.Combine(exporterSettings.DestinationFolder, exporterSettings.FileName);

			using (XmlWriter writer = XmlWriter.Create(fileAndPath))
			{
				writer.WriteStartDocument();
				writer.WriteStartElement("Content");

				ExportCategories(writer, wikiInstance.GetAllCategories());
				ExportPages(writer, wikiInstance.GetAllPages());

				writer.WriteEndElement();
				writer.WriteEndDocument();
			}
		}

		private void ExportPages(XmlWriter writer, IQueryable<WikiPage> allPages)
		{
			writer.WriteStartElement("WikiPages");
			foreach (var wikiPage in allPages)
			{
				writer.WriteStartElement("WikiPage");
				writer.WriteAttributeString("Id", wikiPage.Id.ToString());
				writer.WriteAttributeString("Name", wikiPage.Name);
				writer.WriteAttributeString("Title", wikiPage.Title);
				writer.WriteAttributeString("CategoryId", wikiPage.CategoryId.ToString());
				writer.WriteString(wikiPage.Content);
				writer.WriteEndElement();
			}
			writer.WriteEndElement();
		}

		private void ExportCategories(XmlWriter writer, IQueryable<Category> allCategories)
		{
			writer.WriteStartElement("Categories");
			foreach (var category in allCategories)
			{
				writer.WriteStartElement("Category");
				writer.WriteAttributeString("Id", category.Id.ToString());
				writer.WriteAttributeString("Name", category.Name);
				writer.WriteAttributeString("Description", category.Description);
				writer.WriteEndElement();
			}
			writer.WriteEndElement();
		}
		
		/// <summary>
		/// Performs the complete wiki restore.
		/// </summary>
		/// <param name="settings">The settings.</param>
		/// <param name="wikiInstance">The wiki instance.</param>
		public void PerformCompleteWikiRestore(Dictionary<string, string> settings, IWiki wikiInstance)
		{
			throw new NotImplementedException();
		}
	}
}
